import { useUserStore } from '../stores/user'

// 权限检查工具函数
export const permissionUtils = {
  // 检查用户是否有指定权限
  hasPermission(permissionCode) {
    const userStore = useUserStore()
    return userStore.hasPermission(permissionCode)
  },

  // 检查用户是否有指定角色
  hasRole(roleName) {
    const userStore = useUserStore()
    return userStore.hasRole(roleName)
  },

  // 检查用户是否有任意一个权限
  hasAnyPermission(permissionCodes) {
    const userStore = useUserStore()
    return permissionCodes.some(code => userStore.hasPermission(code))
  },

  // 检查用户是否有所有权限
  hasAllPermissions(permissionCodes) {
    const userStore = useUserStore()
    return permissionCodes.every(code => userStore.hasPermission(code))
  },

  // 检查用户是否有任意一个角色
  hasAnyRole(roleNames) {
    const userStore = useUserStore()
    return roleNames.some(role => userStore.hasRole(role))
  },

  // 检查用户是否有所有角色
  hasAllRoles(roleNames) {
    const userStore = useUserStore()
    return roleNames.every(role => userStore.hasRole(role))
  }
}

// 权限指令
export const permissionDirective = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    
    if (value) {
      let hasPermission = false
      
      if (typeof value === 'string') {
        // 单个权限检查
        hasPermission = userStore.hasPermission(value)
      } else if (Array.isArray(value)) {
        // 多个权限检查
        if (value.length === 0) {
          hasPermission = true
        } else {
          hasPermission = value.some(permission => userStore.hasPermission(permission))
        }
      } else if (typeof value === 'object') {
        // 复杂权限检查
        const { permissions, roles, logic = 'or' } = value
        
        if (logic === 'and') {
          hasPermission = (!permissions || userStore.permissions.every(p => permissions.includes(p))) &&
                        (!roles || userStore.roles.every(r => roles.includes(r)))
        } else {
          hasPermission = (!permissions || permissions.some(p => userStore.hasPermission(p))) ||
                        (!roles || roles.some(r => userStore.hasRole(r)))
        }
      }
      
      if (!hasPermission) {
        el.style.display = 'none'
      }
    }
  }
}

// 角色指令
export const roleDirective = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    
    if (value) {
      let hasRole = false
      
      if (typeof value === 'string') {
        hasRole = userStore.hasRole(value)
      } else if (Array.isArray(value)) {
        hasRole = value.some(role => userStore.hasRole(role))
      }
      
      if (!hasRole) {
        el.style.display = 'none'
      }
    }
  }
} 